<!--
 * @Description: 上传图片组件
 * @Author: Boide
 * @Date: 2021-09-08 10:52:37
 * @LastEditors: guiyi@hongyi.tech
 * @LastEditTime: 2022-02-21 10:39:43
-->
<template>
	<div class="upload-box" :class="{'block': block}">
		<template v-if="multiple">
			<div class="demo-upload-list" v-for="(item, i) in myValue" :key="item.url"  :style="{'background-image': `url('${item.replace(/\s/g, encodeURIComponent(' '))}')`}">
				<div class="demo-upload-list-cover">
          <i class="el-icon-view" @click="handleView(item)"/>
          <i v-if="!show" class="el-icon-delete" @click="handleRemove(i)" />
				</div>
			</div>
		</template>
		<el-upload
      v-if="((multiple&&myValue&&myValue.length<multipleMax&&!show) || !multiple)"
      class="upload-custom"
      :name="name"
      drag
      :action="action"
      :multiple="multiple"
      :disabled="disabled"
      :accept="accept"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
    >
			<div class="upload-custom-box">
				<div v-if="(!myValue||multiple)&&!disabled">
					<i class="el-icon-upload" />
					<p class="el-upload__text">点击或拖拽上传</p>
				</div>
				<div v-else-if="disabled&&!multiple&&myValue" class="img" @click.prevent.stop="handleView(myValue)">
					<img :src="myValue" :alt="myValue">
				</div>
				<div v-else-if="myValue" class="img">
					<img :src="myValue" :alt="myValue">
				</div>
			</div>
			<slot slot="tip" name="tip"></slot>
		</el-upload>
    <el-dialog title="图片预览" :visible.sync="visible" append-to-body>
			<img :src="imgUrl" v-if="visible" style="width: 100%">
		</el-dialog>
	</div>
</template>

<script>
import { getToken } from '@/utils/auth'
/**
 * upload-img 文件上传组件
 * @description 文件上传组件
 * @property {[String, Number, Array]} value 双向绑定值 默认: ''
 * @property {String} action 上传接口地址 默认: ''
 * @property {String} accept 上传文件类型 默认: 'png,jpg,jpeg'
 * @property {Boolean} disabled 是否禁用 默认: false
 * @property {Boolean} multiple 是否多图模式 默认: false
 * @property {Boolean} block 是否一行一个展示 默认: false
 * @property {Boolean} multipleMax 多选展示最多多少个 默认: 6
 * @property {Number} maxSize 文件的最大大小，单位KB 默认: 2048
 */
import './index.scss'
export default {
  name: 'upload-img',
  props: {
    value: [String, Number, Array],
    action: {
      type: String,
      default: () => {
        return `${process.env.VUE_APP_BASE_API}/wx/menu/upload`
      }
    },
    name: {
      type: String,
      default: 'file'
    },
    accept: {
      type: String,
      default: 'png,jpg,jpeg'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    block: {
      type: Boolean,
      default: false
    },
    multipleMax: {
      type: Number,
      default: 3
    },
    maxSize: {
      type: Number,
      default: 1024*5
    },
    show: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      headers: {
        'Authorization': getToken()
      },
      myValue: this.value,
      imgUrl: '',
      visible: false
    }
  },
  watch: {
    value (newVal) {
      this.myValue = newVal
    },
    myValue (newVal) {
      this.$emit('input', newVal)
    }
  },
	computed: {
		fileSize() {
      let value = this.maxSize*1024
			let val = '';
			if (value < 1024) {
				val = value + 'B';
			} else if (value / 1024 < 1024) {
				val = (value / 1024).toFixed(2) + 'KB';
			} else {
				val = value ? (value / 1024 / 1024).toFixed(2) + 'M' : '0B';
			}
			return val;
		}
	},
  methods: {
    handleView (url) {
      this.imgUrl = url
      this.visible = true
    },
    onSuccess ({ data }) {
      let url = data
      if (this.multiple) {
        if (Array.isArray(this.myValue)) {
          this.myValue.push(url)
        } else {
          this.myValue = [url]
        }
      } else {
        this.myValue = url
      }
      this.$emit('input', this.myValue)
    },
    handleRemove (i) {
      this.myValue.splice(i, 1)
      this.$emit('input', this.myValue)
    },
    beforeUpload (file) {
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      const istype = this.accept.indexOf(fileType) !== -1
      const isSize = file.size / 1024 < this.maxSize
      if (!istype) {
        this.$message.warning(`上传的格式只能为；${this.accept}`)
      }
      if (!isSize) {
        this.$message.warning(`上传文件大小不能超过${this.fileSize}`)
      }
      return istype && isSize
    }
  }
}
</script>
